import {
  personInfo,
  addressInfo,
  getDiscount,
  getPackFee,
  getTableWare,
  getDeliveryFee,
  orderAdd,
  defaultAddressInfo,
  paysend
} from "../../../http/api"


const app = getApp()


Page({
  /**
   * 页面的初始数据
   */
  data: {
    oldId: "",
    oldInfo: {},
    addressId: "",
    addressInfo: {},
    todayStr: "",

    discount: 0,
    disType: 0,
    disAmount: 0,

    goodsTotal: 0,

    deliveryFee: 0,
    deliveryFeeOnce: 0,
    deliveryFeeTaoCan: 0,

    packFee: 0,
    packFeeOnce: 0,
    packFeeTaocan: 0,

    orderTotal: 0,

    today: "",
    date: "",
    time: "",
    startTime: "08:00",
    endTime: "20:00",

    memo: "",
  },

  handleCancleOld() {
    this.setData({
      oldId: ""
    })
    wx.removeStorageSync('orderOld')

  },


  clearOrderStorage() {
    // wx.clearStorageSync("")
    wx.removeStorageSync('orderDeliveryDays');
    wx.removeStorageSync('orderStartDate');
    wx.removeStorageSync('orderPlanType');
    wx.removeStorageSync('orderAddress');
    wx.removeStorageSync('orderOld');
    wx.removeStorageSync('orderDateArr');
  },
  handlePay() {

   const that = this

    if (!wx.getStorageSync('orderAddress')) {
      wx.showModal({
        title: '提示',
        content: '请选择收获地址',
        showCancel: false,
      })
      return
    }



    const orderDetailList = this.data.goodsArr.map(item => {
      const goodsObj = {}
      goodsObj.goodName = item.name;
      goodsObj.goodPrice = item.price;
      goodsObj.goodAmount = item.num;
      goodsObj.goodPriceOld = item.oldPrice;
      goodsObj.goodPic = item.image;
      return goodsObj
    });


    let orderDatesStr = ""

    const params = {
      customerId: wx.getStorageSync('id'),
      personId: wx.getStorageSync('orderOld'),
      addressId: wx.getStorageSync('orderAddress'),
      orderType: 0, //订单类型  0-外卖  1-包月  2-堂食  3-餐具押金
      goodPrice: this.data.goodsTotal,
      deliveryPrice: this.data.deliveryFee,
      packPrice: this.data.packFee,
      subsidyPrice: this.data.discount,
      amountPrice: this.data.orderTotal,
      status: 0,
      memo: this.data.memo,
      orderDetailList: orderDetailList,
      startDate: wx.getStorageSync('orderDate'),
      sendTime: this.data.time
    }


    wx.showModal({
      title: '提示',
      content: '确认提交该订单吗？',
      complete: (res) => {
        if (res.confirm) {
          wx.showLoading()
          orderAdd(params).then(res => {
            if (res.data.code == 200) {
              that.clearOrderStorage()

              //消息订阅
              app.userSubscribeMessageTakeoutReceive()
             
              const {id,orderNum,amountPrice} = res.data.data
              wx.redirectTo({
                url: `/pages/user/pay/pay?id=${id}&orderNum=${orderNum}&amountPrice=${amountPrice}&orderType=0`,
              })
              
             
             
            } else {
              wx.showModal({
                title: '提示',
                content: '订单异常请重新提交',
              })
            }
          }).finally(() => {
            wx.hideLoading()
          })

        }
      }
    })

  },

  toPage(e) {
    const {
      url
    } = e.currentTarget.dataset

    wx.navigateTo({
      url
    })
  },




  //更改配送时间
  handleChangeDate(e) {
    const date = e.detail.value
    this.setData({
      date
    })
    wx.setStorageSync('orderDate', date)
  },

  handleChangeTime(e) {
    const time = e.detail.value
    this.setData({
      time
    })
    wx.setStorageSync('orderTime', time)
  },




  //补贴计算器
  discountCalculator() {
    const {
      disType,
      disAmount,
      goodsTotal,
      oldId
    } = this.data

    if (!oldId) {
      return
    }
    let discount = 0

    if (disType == 0) {
      discount = (1 - disAmount) * goodsTotal
    } else {
      discount = disAmount
    }





    this.setData({
      discount: discount.toFixed(1)
    })
    this.orderCalculator()
  },

  //配送费计算器
  deliveryFeeCalculator() {
    const {
      deliveryFeeOnce,
      deliveryDays,
      goodsArr,
      deliveryFeeTaoCan
    } = this.data
    let deliveryFee = deliveryFeeOnce




    this.setData({
      deliveryFee: deliveryFee.toFixed(1)
    })
    this.orderCalculator()
  },


  //打包费计算器
  packFeeCalculator() {
    const {
      packFeeOnce,
      goodsArr,
      packFeeTaoCan
    } = this.data
    let packFee = packFeeOnce




    this.setData({
      packFee: packFee.toFixed(1)
    })
    this.orderCalculator()

  },


  //商品金额计算器
  goodsCalculator() {

    const goodsTotal = this.data.goodsArr.reduce((pre, cur) => {

      return pre + cur.price * cur.num;


    }, 0)

    this.setData({
      goodsTotal: goodsTotal.toFixed(1)
    })
    this.orderCalculator()


  },


  //订单计算器
  orderCalculator() {
    const {
      discount,
      goodsTotal,
      deliveryFee,
      packFee,
      isDeposit,
      deposit
    } = this.data

    let orderTotal = parseFloat(goodsTotal) + parseFloat(deliveryFee) + parseFloat(packFee) - parseFloat(discount);
  


    if (isDeposit) {
      orderTotal = orderTotal + parseFloat(deposit)
    }
    this.setData({
      orderTotal: orderTotal.toFixed(1)
    })
  },




  //初始化打包费
  async initPackFee() {
    wx.showLoading()
    const onceRes = await getPackFee({
      orderType: 0
    });
    const taocanRes = await getPackFee({
      orderType: 1
    });
    if (onceRes.data.code === 200) {
      this.setData({
        packFeeOnce: onceRes.data.data.price
      })
    }
    if (taocanRes.data.code === 200) {
      this.setData({
        packFeeTaoCan: taocanRes.data.data.price
      })
    }
    wx.hideLoading()

    this.packFeeCalculator()





  },

  //初始化配送费
  async initDeliveryFee() {
    //获取单品配送费
    const resOnce = await getDeliveryFee({
      distance: this.data.addressInfo.distance,
      feeType: 0,
      orderType: 0
    })


    if (resOnce.data.code === 200) {
      this.setData({
        deliveryFeeOnce: resOnce.data.data
      })
    }

    //获取套餐配送费
    const resTaoCan = await getDeliveryFee({
      distance: this.data.addressInfo.distance,
      feeType: 0,
      orderType: 1
    })

    if (resTaoCan.data.code === 200) {
      this.setData({
        deliveryFeeTaoCan: resTaoCan.data.data
      })
    }
    this.deliveryFeeCalculator()

  },


  initDate() {
    const today = new Date();
    let year = today.getFullYear();
    let month = today.getMonth() + 1;
    let date = today.getDate();
    let hour = today.getHours();
    let minute = today.getMinutes();
    if (month < 10) {
      month = '0' + month
    }
    if (date < 10) {
      date = '0' + date
    }

    if (hour < 10) {
      hour = '0' + hour
    }
    if (minute < 10) {
      minute = '0' + minute
    }


    const res = `${year}-${month}-${date}`;
    const time = `${hour}:${minute}`
    this.setData({
      today: res,
      date: res,
      time: time,
    })
    wx.setStorageSync('orderDate', res)
  },

  // 初始化
  async initData() {

    const goodsArr = wx.getStorageSync('cart');
    const oldId = wx.getStorageSync('orderOld');
    const addressId = wx.getStorageSync('orderAddress');


    this.setData({
      goodsArr
    })

    this.initPackFee()
    this.initDate()
    this.goodsCalculator()


    //是否有老人缓存
    if (oldId) {
      this.setData({
        oldId
      })
      wx.showLoading()
      const oldRes = await personInfo(oldId)

      if (oldRes.data.code === 200) {
        this.setData({
          oldInfo: {
            ...oldRes.data.data
          }
        })

        const discountRes = await getDiscount({
          idcard: oldRes.data.data.idcard
        })

        if (discountRes.data.code === 200) {
          const {
            disType,
            amount
          } = discountRes.data.data;
          this.setData({
            disType,
            disAmount: amount
          })
        }

        this.discountCalculator()
        this.orderCalculator()

        wx.hideLoading()
      }

    }


    //是否有地址缓存
    if (addressId) {
      this.setData({
        addressId
      })
      this.getAddressInfo(addressId);
    } else {
      this.getDefaultAddressInfo()
    }

  },


  //获取默认地址信息
  getDefaultAddressInfo() {
    wx.showLoading()
    defaultAddressInfo({
      customerId: wx.getStorageSync('id')
    }).then(res => {
      if (res.data.code === 200) {
        this.setData({
          addressInfo: {
            ...res.data.data
          }
        })
        this.setData({
          addressId: res.data.data.id
        })
        wx.setStorageSync('orderAddress', res.data.data.id)
        this.initDeliveryFee()


      }
    }).finally(() => {
      wx.hideLoading()
    })
  },

  getAddressInfo(addressId) {
    wx.showLoading()
    addressInfo(addressId).then(res => {
      if (res.data.code === 200) {
        this.setData({
          addressInfo: {
            ...res.data.data
          }
        })
        this.initDeliveryFee()
      }
    }).finally(() => {
      wx.hideLoading()
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {



  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {


    this.initData()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})